package com.dmall.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Jpa配置类
 *
 * @author xiao1.wang@dmall.com
 * @date 2019-03-21 18:26:53
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.dmall.dao")
@PropertySource(value = "classpath:datasource.properties")
@Slf4j
public class JpaConfig {

    @Autowired
    private Environment environment;

    /**
     * 通过数据库连接池配置数据源
     * 具体配置选项可以查看
     * druid连接池的指南
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(environment.getProperty("db.url"));
        dataSource.setUsername(environment.getProperty("db.username"));
        dataSource.setPassword(environment.getProperty("db.password"));
        dataSource.setDriverClassName(environment.getProperty("db.driverClass"));
        dataSource.setTimeBetweenEvictionRunsMillis(
                Integer.valueOf(environment.getProperty("db.timeBetweenEvictionRunsMillis")));
        dataSource.setPoolPreparedStatements(true);
        dataSource.setInitialSize(Integer.valueOf(environment.getProperty("db.initialSize")));
        dataSource.setMinIdle(Integer.valueOf(environment.getProperty("db.minIdle")));
        dataSource.setMaxActive(Integer.valueOf(environment.getProperty("db.maxActive")));
        dataSource.setValidationQuery(environment.getProperty("db.validationQuery"));
        dataSource.setMaxWait(Long.valueOf(environment.getProperty("db.maxWait")));
        dataSource.setTestWhileIdle(Boolean.getBoolean(
                environment.getProperty("db.testWhileIdle")));

        try {
            dataSource.init();
        } catch (SQLException e) {
            log.error("数据库连接池启动异常 {}", e);
            throw new RuntimeException(e);
        }
        return dataSource;
    }

    /**
     * 启用JPA事务管理器
     */
    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }


    /**
     * 启用JPA数据适配器
     * 并指明数据库类型为MySQL
     * 自动生成表为false 这个属性在后面JPA属性里配置
     */
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setDatabase(Database.H2);
        jpaVendorAdapter.setGenerateDdl(true);
        jpaVendorAdapter.setShowSql(true);
        return jpaVendorAdapter;
    }

    /**
     * 配置JPA持久化工厂属性
     * 设置扫描的数据模型包xyz.my.model
     * 配置JPA属性 hibernate.format_sql 格式化SQL语句为true
     * 配置JPA属性 hibernate.hbm2ddl.auto 自动生成表为validate(校验模式)
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.dmall.domain");
        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.format_sql", "true");
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        entityManagerFactoryBean.setJpaProperties(jpaProperties);
        return entityManagerFactoryBean;
    }
}